package com.nifostasky.main.thread.create;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 创建 : 通过Callable创建线程;
 */
public class CreateCallable {
    /**
     * *与Runnable相比，Callable功能更强大**
     *
     * 1. 相比`run()`方法，`call()`可以有返回值
     * 2. 方法可以抛出异常
     * 3. 支持泛型的返回值
     * 4. 需要借助`FutureTask`类来获取返回结果
      */
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        System.out.println("===============================================================================");

        //创建一个线程体
        myCallable myCallable = new myCallable();

        //创建一个FutureTask 构造器
        FutureTask<Integer> integerFutureTask = new FutureTask<>(myCallable);

        /**
         * 此方法会阻塞,直到 call方法执行完毕返回值
         */
        //将FutureTask的对象作为参数传递到Thread类的构造器中，创建Thread对象，并调用start()
        new Thread(integerFutureTask).start();

        Integer integer = integerFutureTask.get();
        System.out.println("总计:" + integer);

        System.out.println("===============================================================================");


    }
}

class myCallable implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i < 100; i++) {
            if(i%2==0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}